package com.moriarty.socketim.activity;

import android.app.Activity;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.moriarty.socketim.IMApplication;
import com.moriarty.socketim.R;
import com.moriarty.socketim.core.OnMessageListener;
import com.moriarty.socketim.core.QQConnection;
import com.moriarty.socketim.entity.BuddyInfo;
import com.moriarty.socketim.entity.QQMessage;
import com.moriarty.socketim.entity.QQMessageType;
import com.moriarty.socketim.util.ThreadUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;

/**
 * Created by Moriarty on 16/11/17.
 */
public class BuddyListActivity extends BaseActivity {

    private ArrayList<BuddyInfo> list_buddy = new ArrayList<BuddyInfo>();
    private ListView mLvBuddyList;
    private long username;
    private BuddyAdapter mBuddyAdapter;

    OnMessageListener listener = new OnMessageListener() {
        @Override
        public void onGetMessage(QQMessage msg) {
            if (msg.type.equals(QQMessageType.MSG_TYPE_BUDDY_LIST)) {
                //解析更新过来的json串
                parseBuddyJsonToList(msg.content);
                //更新界面 要放到主线程
                ThreadUtil.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        //根据这个信息更新adapter 从而更新界面
                        if (mBuddyAdapter != null) {
                            mBuddyAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_buddylist);
        mLvBuddyList = (ListView) findViewById(R.id.lv_buddylist);

        IMApplication imApplication = (IMApplication) getApplication();
        QQConnection qqConnection = imApplication.getQqConnection();
        username = Long.parseLong(imApplication.getUsername());

        Log.e("fuck", qqConnection + String.valueOf(username));

        //好友上线后 需要刷新本地好友列表
        //此时 新的好友列表已经由服务器传输过来 只需要搞一个监听器监听 拿到信息后解析然后刷新即可

        //获取传递过来的json字符串
        String json_buddylist = getIntent().getStringExtra("buddylistjson");
        //解析json串
        parseBuddyJsonToList(json_buddylist);

        mBuddyAdapter = new BuddyAdapter();
        mLvBuddyList.setAdapter(mBuddyAdapter);
        mLvBuddyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BuddyInfo buddyInfo = list_buddy.get(position);
                Intent intent = new Intent(getBaseContext(), ChatActivity.class);
                intent.putExtra("buddyInfo", buddyInfo);
                startActivity(intent);
            }
        });
    }

    private void parseBuddyJsonToList(String json_buddylist) {
        //解析json
        try {
            //每次使用list之前要clear一下 把上次搞出来是list清空内容
            list_buddy.clear();
            JSONObject blist_jsonobj = new JSONObject(json_buddylist);
            JSONArray buddyList = blist_jsonobj.getJSONArray("buddyList");
            for (int i = 0; i < buddyList.length(); i++) {
                JSONObject buddyListJSONObject = buddyList.getJSONObject(i);
                BuddyInfo buddyInfo = new BuddyInfo();
                buddyInfo.setAccount(buddyListJSONObject.getLong("account"));
                buddyInfo.setNick(buddyListJSONObject.getString("nick"));
                buddyInfo.setAvatar(buddyListJSONObject.getInt("avatar"));
                //把自己剔除（好友列表中不要显示自己）
                if (buddyInfo.getAccount() != username) {
                    list_buddy.add(buddyInfo);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private class BuddyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list_buddy.size();
        }

        @Override
        public Object getItem(int position) {
            return list_buddy.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(getApplicationContext(), R.layout.item_buddylist, null);
                viewHolder.iv_header = (ImageView) convertView.findViewById(R.id.iv_head);
                viewHolder.tv_account = (TextView) convertView.findViewById(R.id.tv_buddyname);
                viewHolder.tv_status = (TextView) convertView.findViewById(R.id.tv_status);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

//            viewHolder.iv_header.setImageResource(list_buddy.get(position).getAvatar() == 0 ? R.drawable.ic_launcher : list_buddy.get(position).getAvatar());
            viewHolder.iv_header.setImageResource(R.drawable.ic_launcher);
            Log.e("fuck", list_buddy.get(position).getAccount() + "");
            //记住！要转换成String而不是int！虽然编译的时候也没有报错！但最后运行的时候会出现android.content.res.Resources$NotFoundException: String resource ID #0x65
            viewHolder.tv_account.setText(String.valueOf(list_buddy.get(position).getAccount()));//android.content.res.Resources$NotFoundException: String resource ID #0x65
            viewHolder.tv_status.setText(list_buddy.get(position).getNick());

            return convertView;
        }

        class ViewHolder {
            ImageView iv_header;
            TextView tv_account;
            TextView tv_status;
        }
    }
}
